/**
 * 
 */
package com.tunan.config;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;



/**
 * <b>seqhilo</b><br>
 * <br>
 * An <tt>IdentifierGenerator</tt> that combines a hi/lo algorithm with an
 * underlying oracle-style sequence that generates hi values. The user may
 * specify a maximum lo value to determine how often new hi values are fetched.<br>
 * <br>
 * If sequences are not available, <tt>TableHiLoGenerator</tt> might be an
 * alternative.<br>
 * <br>
 * Mapping parameters supported: sequence, max_lo, parameters.
 * 
 * @see TableHiLoGenerator
 * @author Gavin King
 */
public final class SequenceHiLoGenerator {

	private static final Log log = LogFactory
			.getLog(SequenceHiLoGenerator.class);

	private int maxLo;
	private int lo;
	private long hi;

	public SequenceHiLoGenerator() {
		maxLo = 99;
		lo = maxLo + 1; // so we "clock over" on the first invocation
	}

	public synchronized long generate(String sequenceName) {
		if (maxLo < 1 || com.tunan.common.Environment.isDebug()) {
			long val = SequenceKeyFcatory.getInstance().getNextValue(
					sequenceName);
			return val;
		}
		if (lo > maxLo) {
			long hival = SequenceKeyFcatory.getInstance().getNextValue(
					sequenceName);
			lo = (hival == 0) ? 1 : 0;
			hi = hival * (maxLo + 1);
			if (log.isDebugEnabled())
				log.debug("new hi value: " + hival);
		}

		return hi + lo++;
	}

}
